import requests
from bs4 import BeautifulSoup
import crawlingNationalCityIDNumbers


# 根据城市名称返回html文本
def obtainHtml(cityName):
    # 查询cityId
    cityId = crawlingNationalCityIDNumbers.queryCityIdByCityNameFromMysql(cityName=cityName)
    if cityId != "查不到此地方！":
        # 请求网址
        url = f"http://www.weather.com.cn/weather/{cityId}.shtml"
        headers = {
            "Accept": "text / html, application / xhtml + xml, application / xml;q = 0.9, image / avif, "
                      "image / webp, image / apng, * / *;q = 0.8, application / signed - exchange;v = b3;q = 0.7 ",
            "Accept - Encoding": "gzip, deflate",
            "Accept - Language": "zh - CN, zh;q = 0.9",
            "User - Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / "
                            "114.0.0.0Safari / 537.36 "
        }
        # 发送请求
        res = requests.get(headers=headers, url=url, timeout=30)
        res.encoding = "utf-8"
        # 获取html文本
        html = res.text
        # 返回html文本
        return html
    else:
        return "查不到此地方！"


# 解析HTML文本，获取天气相关信息
def queryWeather(html):
    try:
        # 使用bs4解析html文本
        bs = BeautifulSoup(html, "html.parser")
        body = bs.body
        # 获取class=t clearfix的ul标签
        ul = body.find("ul", {"class": "t clearfix"})
        # 获取ul中的全部li标签
        liAll = ul.findAll("li")

        weatherData = []
        for li in liAll:
            weatherDataOneDay = {}
            date = li.h1.string
            p = li.findAll("p")
            weather = p[0].string
            p2 = p[1]
            if p2.span:
                temperatureMax = p2.span.string
            else:
                temperatureMax = "暂无信息"
            if p2.i:
                temperatureMin = p2.i.string
            else:
                temperatureMin = "暂无信息"
            p3 = p[2]
            em = p3.em
            span = em.findAll("span")
            windDirectionList = []
            for sp in span:
                windDirection = sp["title"]
                windDirectionList.append(windDirection)
            windDirection = " ".join(windDirectionList)
            i = p3.i
            windSpeed = i.string

            weatherDataOneDay["日期"] = date
            weatherDataOneDay["天气"] = weather
            weatherDataOneDay["最高温度"] = temperatureMax
            weatherDataOneDay["最低温度"] = temperatureMin
            weatherDataOneDay["风向"] = windDirection
            weatherDataOneDay["风速"] = windSpeed
            weatherData.append(weatherDataOneDay)
        # print(weatherData)

        return weatherData
    except AttributeError:
        return "查不到此地方！"


# 解析html，获取生活指数
def queryLivingIndex(html):
    try:
        # 使用bs4解析html文本
        bs = BeautifulSoup(html, "html.parser")
        body = bs.body

        livingIndexList = []
        div = body.find("div", {"id": "livezs"})
        divAll = div.findAll("div", {"class": {"hide show", "hide"}})
        for dv in divAll:
            livingIndexOneDayDist = {}
            ul = dv.ul
            liAll1 = ul.findAll("li")
            for l in liAll1:
                if not l.a:
                    em = l.em.string
                    span = l.span.string
                    p = l.p.string
                    livingIndexOneDayDist[em] = f"{span}:{p}"
                else:
                    a = l.a
                    em = a.em.string
                    span = a.span.string
                    p = a.p.string
                    livingIndexOneDayDist[em] = f"{span}:{p}"
            livingIndexList.append(livingIndexOneDayDist)

        # print(livingIndexList)

        return livingIndexList
    except AttributeError:
        return "查不到此地方！"


if __name__ == '__main__':
    html = obtainHtml(cityName="安仁")
    # print(html)
    data = queryWeather(html=html)
    print(data)
